package top.zlhy7.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author 任勇
 * @date 2020/12/10 23:21
 * @description 安全配置
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 密码加密器
     */
    @Autowired
    private PasswordEncoder passwordEncoder;
    /**
     * 数据库查询用户
     */
    @Autowired
    private UserDetailsService userDetailsService;
    /**
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //其第二种方式实现添加用户
//        auth.inMemoryAuthentication()
//                .withUser("user")
//                .password(passwordEncoder.encode("123456"))
//                .roles("admin");
        //设置数据库查询用户
        auth.userDetailsService(userDetailsService)
                //设置密码编码器
                .passwordEncoder(passwordEncoder);
    }

    /**
     * 密码加密器，安全框架要调用的密码加密器
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
